package io.yunho.jddns.component;

import cn.hutool.core.date.DateUtil;
import io.yunho.jddns.service.DdnsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author: Jason
 * @date: 2021/1/21 17:46
 * @description:
 */
@Slf4j
@Component
@ComponentScan("io.yunho.jddns.component")
public class DynamicScheduledTask implements SchedulingConfigurer {
    @Resource
    private JDDnsProperties jdDnsProperties;
    @Resource
    private DdnsService ddnsService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                log.info("*****confirm开始****\t");
                ddnsService.confirmIp(jdDnsProperties);
                log.info("****confirm结束\tgetDdnsIp开始*****\t");
                ddnsService.getDdnsIp(jdDnsProperties);
                log.info("****getDdnsIp结束*****\t");
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {//设置下次定时器
                String cron=jdDnsProperties.getCron();
                log.info("*********\t"+cron);
                CronTrigger trigger = new CronTrigger(cron); // 定时任务触发，可修改定时任务的执行周期
                Date nextExecDate = trigger.nextExecutionTime(triggerContext);
                log.info("****nextExecDate*****\t"+nextExecDate);
                return nextExecDate;
            }
        });
    }
}
